<!-- 菜谱编辑弹窗 -->
<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <a-form
        ref="form2"
        :model="vegetableMenuModalApp.vegetableMenu"
        :rules="vegetableMenuModalApp.rules"
        :label-col="{md: {span: 7}, sm: {span: 24}}"
        :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :sm="24" :xs="24">
            <a-form-item label="菜谱名称:" name="contactTel">
              <a-input
                :disabled="!vegetableMenuModalApp.display||!vegetableMenuListApp.whetherAdmin"
                v-model:value="vegetableMenuModalApp.vegetableMenu.name"
                placeholder="请输入菜谱名称"
                :maxlength="255"
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :lg="12" :md="12" :sm="24" :xs="24">
            <a-form-item label="菜谱定价:" name="contactTel">
              <a-input-number
                :disabled="!vegetableMenuModalApp.display"
                v-model:value="vegetableMenuModalApp.vegetableMenu.price"
                placeholder="请输入菜谱定价"
                :maxlength="255"
                allow-clear
                :formatter="value=>Number(`${value}`).toFixed(2)"
              />
            </a-form-item>
          </a-col>


        </a-row>

        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item :wrapper-col="{md: {offset: 6}}" style="margin-bottom: -20px">
            <!--class="ele-pull-right"-->
            <teleport to="#vegetableMenuEditModalFooter">
              <div>
                <a-space size="middle">
                  <a-button @click="vegetableMenuListApp.modalShowing=false">取消
                  </a-button>
                  <a-button
                    v-if="vegetableMenuModalApp.display"
                    type="primary"
                    @click="onSubmit(vegetableMenuModalApp.vegetableMenu)"
                    :loading="loading">提交
                  </a-button>
                </a-space>
              </div>
            </teleport>
          </a-form-item>
        </a-col>

      </a-form>
    </a-card>

    <vxe-toolbar>
      <template #buttons>
        <span style="color: black;font-size: 15px;font-weight: bolder !important;">
          <i class="fa fa-pencil-square-o" aria-hidden="true">&nbsp;
          </i>菜谱材料管理</span>
        <span> 最高成本价格：<span style="color: red">{{ maxCostPrice }}</span>元</span>

      </template>
      <template #tools v-if="vegetableMenuModalApp.display&&vegetableMenuListApp.whetherAdmin">
        <vxe-button @click="insertEvent(-1)">新增菜谱材料</vxe-button>
        <vxe-button @click="$refs.xTable.removeCheckboxRow()">删除选中菜谱材料</vxe-button>
<!--        <vxe-button icon="fa fa-save" @click="saveEvent">保存</vxe-button>-->
      </template>
    </vxe-toolbar>

    <vxe-table
      border
      show-overflow
      keep-source
      ref="xTable"
      max-height="400"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil', showStatus: true, enabled: vegetableMenuModalApp.display&&vegetableMenuListApp.whetherAdmin}">
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" width="60"></vxe-column>
      <vxe-column field="materialName" title="材料"
                  :edit-render="{}">
        <!--        autofocus: '.vxe-input&#45;&#45;inner', defaultValue: '默认的名字'-->
        <template #edit="{ row }">
          <!--          <vxe-input v-model="row.materialName" type="text"></vxe-input>-->
          <vxe-select v-model="row.materialName" @change="({ value, $event }) => {
      row.materialName=value.name;
      row.materialId=value.eid;
      row.maxPrice=value.maxPrice;
      computingCosts();
    }" transfer>
            <vxe-option v-for="item in vegetableMenuModalApp.materials" :key="item.eid" :value="item"
                        :label="item.name"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>
      <vxe-column field="amount" title="数量(kg)" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ row.amount }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-input v-model="row.amount" type="text" @change="computingCosts"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="remark" title="备注" sortable :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.remark" type="text"></vxe-input>
        </template>
      </vxe-column>
    </vxe-table>

  </div>

</template>

<script>
import {defineComponent, inject, reactive, onMounted, ref} from 'vue'
import {useRoute} from "vue-router"
import {VegetableMenuService} from "@/views/restaurant/sale/vegetableMenu/vegetableMenuService";
import {MaterialService} from "@/views/restaurant/material/material/materialService";
import regions from 'ele-admin-pro/packages/regions.js';
import {VXETable} from 'vxe-table'
import {
  MenuMaterialRelationShipService
} from "@/views/restaurant/sale/menuMaterialRelationShip/menuMaterialRelationShipService";

export default defineComponent({
  // components: {MEntitySelect},
  setup() {
    // 省市区数据
    const cityData = regions
    const route = useRoute();
    const maxCostPrice = ref(0);
    let routeId = route.params.id;
    let vegetableMenuListApp = inject('vegetableMenuListApp', reactive({}));
    let vegetableMenuGrid = inject('vegetableMenuGrid', ref())
    const vegetableMenuModalApp = reactive({
      id: null,
      vegetableMenu: {},
      isEdit: false,
      display: false
    });
    vegetableMenuModalApp.rules = {}

    onMounted(() => {
      //清理数据
      vegetableMenuModalApp.vegetableMenu = reactive({});
      MaterialService.findMaterials({currentPage: 1, filters: {}, orderBys: [], pageSize: 100}).then((res) => {
        vegetableMenuModalApp.materials = res.data.datas;
      })

      if (routeId) {//路由
        vegetableMenuModalApp.id = routeId;
        vegetableMenuModalApp.display = false;
        findVegetableMenu(vegetableMenuModalApp.id);
      } else if (vegetableMenuListApp.editModalForEdit) {//修改弹窗
        vegetableMenuModalApp.id = vegetableMenuListApp.currentId;
        vegetableMenuModalApp.display = true;
      } else if (!vegetableMenuListApp.editModalForEdit && vegetableMenuListApp.addModalForEdit) {//新增弹窗
        vegetableMenuModalApp.display = true;
      } else if (!vegetableMenuListApp.editModalForEdit && !vegetableMenuListApp.addModalForEdit && vegetableMenuListApp.showModalForEdit) {
        vegetableMenuModalApp.id = vegetableMenuListApp.currentId;
        vegetableMenuModalApp.display = false;
      }
      if (vegetableMenuModalApp.id) findVegetableMenu(vegetableMenuModalApp.id);

    })

    const findVegetableMenu = (id) => {
      VegetableMenuService.findVegetableMenuForView(id).then((res) => {
        vegetableMenuModalApp.vegetableMenu = res.data;
        vegetableMenuModalApp.vegetableMenu.price = Number(vegetableMenuModalApp.vegetableMenu.price).toFixed(2)
        tableData.value = res.data.menuMaterials
        console.log("数据", res.data)
        //TODO:为编辑准备.
        vegetableMenuModalApp.title = "编辑 " + vegetableMenuModalApp.vegetableMenu.name;
      }).then(()=>{
        computingCosts()
      }).catch(error => {
        VXETable.modal.message({content: `查找出错，原因是：${error.message}`, status: 'error'});
      })

    }
    const computingCosts = () => {
      const $table = xTable.value
      let tableData = $table.getTableData()
      let totalCost = 0;
      tableData.tableData.forEach((data) => {
        totalCost += data.maxPrice * data.amount;
      })
      console.log("成本价格为：" + totalCost)
      maxCostPrice.value = totalCost.toFixed(2);
      vegetableMenuModalApp.vegetableMenu.cost = totalCost
    }

    /*TODO:提交 新增&编辑*/
    const onSubmit = (data) => {
      // debugger;
      //当为数组时用逗号连接
      //获取材料
      const $table = xTable.value
      const {insertRecords, removeRecords, updateRecords} = $table.getRecordset()
      console.log(removeRecords, updateRecords, insertRecords)
      if (data.eid) {
        //修改
        VegetableMenuService.updateVegetableMenu(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
        MenuMaterialRelationShipService.batchHandle(insertRecords, removeRecords, updateRecords).then(() => {
          // VXETable.modal.message({content: '操作成功', status: 'success'});
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      } else {
        //新增
        data.menuMaterials = insertRecords
        VegetableMenuService.saveVegetableMenu(data).then((res) => {
          console.log(res);
          VXETable.modal.message({content: '操作成功', status: 'success'});
          setTimeout(onBack, 3000);
        }).catch(error => {
          VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
        })
      }
    }

    /*TODO:继续提交*/
    const continueSubmit = () => {
      VXETable.modal.message({content: 'error 提示', status: 'error'});
    }

    /*TODO:返回列表*/
    const onBack = () => {
      console.log("back")
      setTimeout(() => {
        vegetableMenuGrid.value.commitProxy("query");
      }, 1500);
      vegetableMenuListApp.modalShowing = false;
    }

    const xTable = ref({})

    const tableData = ref([])


    const insertEvent = async (row) => {
      const $table = xTable.value
      const record = {
        menuId: vegetableMenuModalApp.vegetableMenu.eid
      }
      const {row: newRow} = await $table.insertAt(record, row)
      await $table.setActiveCell(newRow, 'name')
    }

    const getInsertEvent = () => {
      const $table = xTable.value
      const insertRecords = $table.getInsertRecords()
      VXETable.modal.alert(`新增：${insertRecords.length}`)
    }

    const getSelectionEvent = () => {
      const $table = xTable.value
      const selectRecords = $table.getCheckboxRecords()
      VXETable.modal.alert(`选中：${selectRecords.length}`)
    }

    const saveEvent = () => {
      const $table = xTable.value
      const {insertRecords, removeRecords, updateRecords} = $table.getRecordset()
      VXETable.modal.alert(`insertRecords=${insertRecords.length} removeRecords=${removeRecords.length} updateRecords=${updateRecords.length}`)
      console.log("insertRecords", insertRecords)
    }

    return {
      cityData,
      routeId,
      vegetableMenuListApp,
      vegetableMenuModalApp,
      onSubmit,
      continueSubmit,
      onBack,
      xTable,
      tableData,
      insertEvent,
      getInsertEvent,
      getSelectionEvent,
      saveEvent,
      computingCosts,
      maxCostPrice
      // changeMaterial
    }

  },
})
</script>

<style scoped>

</style>
